package com.zwj.batch.core.batch.step.processor;

import com.zwj.batch.core.service.UserService;
import com.zwj.batch.domain.po.UserPO;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.adapter.ItemProcessorAdapter;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.batch.item.validator.BeanValidatingItemProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 校验策略
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2023-06-27 14:08:00
 */
@Component
public class UserProcessor {
    @Resource
    private UserService userService;
    @Resource
    private BeanValidatingItemProcessor<UserPO> beanValidatingItemProcessor;

    /**
     * name字段转换为大写
     *
     * @return
     */
    public ItemProcessorAdapter<UserPO, UserPO> userProcessor() {
        ItemProcessorAdapter<UserPO, UserPO> adapter = new ItemProcessorAdapter<UserPO, UserPO>();
        adapter.setTargetObject(userService);
        adapter.setTargetMethod("toUppeCase");
        return adapter;
    }

    /**
     * 组合处理器，字段大写的处理 + 读取文件信息校验的处理
     *
     * @return
     */
    public CompositeItemProcessor<UserPO, UserPO> compositeItemProcessor() {
        CompositeItemProcessor<UserPO, UserPO> compositeItemProcessor = new CompositeItemProcessor<>();
        compositeItemProcessor.setDelegates(Arrays.asList(
                userProcessor(),
                beanValidatingItemProcessor
        ));
        return compositeItemProcessor;
    }

    /**
     * 自定义处理器，筛选用户 id 为偶数的 user
     *
     * @return
     */
    public ItemProcessor<? super UserPO, ? extends UserPO> customizeItemProcessor() {
        return new ItemProcessor<UserPO, UserPO>() {
            @Override
            public UserPO process(UserPO userPO) throws Exception {
                return userPO.getId() % 2 == 0 ? userPO : null;
            }
        };
    }
}
